package com.iot.manager.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.iot.manager.data.models.DeviceConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.EnumMap;
import java.util.Map;

public class QRCodeUtils {
    private static final String TAG = "QRCodeUtils";

    /**
     * 从图片中解码二维码
     * @param context 上下文
     * @param imageUri 图片URI
     * @return 二维码内容，如果解码失败则返回null
     */
    public static String decodeQRCodeFromImage(Context context, Uri imageUri) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
            if (inputStream == null) {
                return null;
            }

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap == null) {
                return null;
            }

            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int[] pixels = new int[width * height];
            bitmap.getPixels(pixels, 0, width, 0, 0, width, height);

            RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

            Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

            Result result = new MultiFormatReader().decode(binaryBitmap, hints);
            return result.getText();
        } catch (IOException e) {
            Log.e(TAG, "Error reading image", e);
            return null;
        } catch (NotFoundException e) {
            Log.e(TAG, "QR code not found in image", e);
            return null;
        } catch (Exception e) {
            Log.e(TAG, "Error decoding QR code", e);
            return null;
        }
    }

    /**
     * 生成设备配网二维码内容
     * @param deviceId 设备ID
     * @param name 设备名称
     * @param type 设备类型
     * @param password 设备密码
     * @param macAddress MAC地址
     * @param firmwareVersion 固件版本
     * @return 二维码内容字符串
     */
    public static String generateDeviceQRContent(String deviceId, String name, String type,
                                               String password, String macAddress, String firmwareVersion) {
        // 使用冒号分隔的格式，确保所有字段都不包含冒号
        return String.format("%s:%s:%s:%s:%s:%s",
                deviceId.replace(":", ""),
                name.replace(":", ""),
                type.replace(":", ""),
                password.replace(":", ""),
                macAddress.replace(":", ""),
                firmwareVersion.replace(":", ""));
    }

    /**
     * 解析设备配网二维码内容
     * @param qrContent 二维码内容
     * @return 解析后的设备信息数组，如果解析失败则返回null
     */
    public static String[] parseDeviceQRContent(String qrContent) {
        if (qrContent == null || qrContent.isEmpty()) {
            return null;
        }

        String[] parts = qrContent.split(":");
        if (parts.length != 6) {
            return null;
        }

        return parts;
    }

    public static DeviceConfig parseQRCode(String qrContent) {
        try {
            JSONObject json = new JSONObject(qrContent);
            DeviceConfig config = new DeviceConfig();

            // 解析设备热点信息
            if (json.has("hotspot")) {
                JSONObject hotspot = json.getJSONObject("hotspot");
                config.setHotspotSsid(hotspot.getString("ssid"));
                config.setHotspotPassword(hotspot.getString("password"));
            }

            // 解析服务器配置
            if (json.has("server")) {
                JSONObject server = json.getJSONObject("server");
                config.setServerUrl(server.getString("url"));
                config.setServerPort(String.valueOf(server.getInt("port")));
            }

            // 解析WiFi配置
            if (json.has("wifi")) {
                JSONObject wifi = json.getJSONObject("wifi");
                config.setWifiSsid(wifi.getString("ssid"));
                config.setWifiPassword(wifi.getString("password"));
            }

            return config;
        } catch (JSONException e) {
            Log.e(TAG, "Error parsing QR code content", e);
            return null;
        }
    }
} 